package com.weblog.weblog.jwt.service;

import com.weblog.weblog.common.domain.dos.UserDO;
import com.weblog.weblog.common.domain.dos.UserRoleDO;
import com.weblog.weblog.common.domain.mapper.UserMapper;
import com.weblog.weblog.common.domain.mapper.UserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * @author gc
 * @class_name UserDetailServiceImpl
 * @date 2023年09月15日 19:57
 */

@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    private final UserRoleMapper userRoleMapper;

    public UserDetailServiceImpl(UserMapper userMapper, UserRoleMapper userRoleMapper) {
        this.userMapper = userMapper;
        this.userRoleMapper = userRoleMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDO userDO = userMapper.findByUsername(username);

        if(Objects.isNull(userDO)){
            throw new UsernameNotFoundException("该用户不存在");
        }
        //用户角色
        List<UserRoleDO> userRoleDOS = userRoleMapper.selectByUsername(username);

        String[] roleArr = null;

        //转数组
        if(!CollectionUtils.isEmpty(userRoleDOS)){
            roleArr = userRoleDOS.stream().map(UserRoleDO::getRole).toArray(String[]::new);
        }

        if(roleArr == null){
            roleArr = new String[]{"ROLE_VISITOR"};
        }

        //authorities 用与指定对象
        return User.withUsername(userDO.getUsername())
                .password(userDO.getPassword())
                .authorities(roleArr)
                .build();

    }
}
